package cn.hgd11.security.config;

import cn.hgd11.security.common.CommonResult;
import cn.hgd11.security.common.Constant;
import cn.hgd11.security.enums.GlobalCodeEnum;
import cn.hgd11.security.util.StringUtils;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author wangkaige
 */
@EnableWebSecurity(debug = true)
public class Hgd11SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService hgd11UserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hgd11UserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .formLogin()
                .successHandler((request, response, authentication) -> {
                    ServletUtil.write(response, JSONObject.toJSONString(CommonResult.success(authentication)), MediaType.APPLICATION_JSON_UTF8_VALUE);
                })
                .failureHandler((request, response, exception) -> {
                    ServletUtil.write(response, JSONObject.toJSONString(CommonResult.error(GlobalCodeEnum.UNAUTHORIZED.getCode(), "登陆异常")), MediaType.APPLICATION_JSON_UTF8_VALUE);
                })
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }

    private String api(String login) {
        return Constant.CONTENT_PATH + "/" + StringUtils.removeStart(login, "/");
    }
}
